import * as d3 from 'd3'
export class River {
  chart = {}
  constructor(divId, vue) {
    this.divId = divId
    this.vue = vue
    if (!d3.select('#' + this.divId).select('svg').empty()) {
      d3.select('#' + this.divId).select('svg').remove()
    }
  }

  draw(cityvalue, citymain) {
    // console.log(cityvalue)
    // console.log(citymain)
    // console.log(this.divId)
    this.drawChart(cityvalue, citymain)
  }
  drawChart(cityvalue, citymain) {
    this.chart.padding = {
      left: 20,
      right: 20,
      top: 10,
      bottom: 10
    }
    this.chart.padding2 = {
      left: 0,
      right: 10,
      top: 10,
      bottom: 10
    }
    this.chart.divHeight = document.getElementById(this.divId).offsetHeight
    this.chart.divWidth = document.getElementById(this.divId).offsetWidth
    // console.log(this.chart.divHeight, this.chart.divWidth)
    this.chart.svg = d3.select('#' + this.divId).append('svg')
      .attr('width', this.chart.divWidth)
      .attr('height', this.chart.divHeight)
      .attr('class', 'svg_chart')
    var mainChart = this.chart.svg.append('g')
      .attr('class', 'main-chart')
      .attr('transform', 'translate(30,0)')
    var miniChart = this.chart.svg.append('g')
      .attr('class', 'mini-chart')
      .attr('transform', 'translate(10,0)')

    var ticks = []
    var citygroup = []
    var datadate = []
    for (var key in cityvalue[0]) {
      if (key !== 'date') {
        citygroup.push(key)
      }
    }
    for (var i = 0; i < cityvalue.length; i++) {
      datadate.push(cityvalue[i].date)
    }
    // console.log(datadate)
    var series = d3.stack()
      .keys(citygroup)
      .offset(d3.stackOffsetWiggle)
      .order(d3.stackOrderInsideOut)(cityvalue)

    var yScale = d3.scaleBand()
      .domain(datadate)
      .range([this.chart.padding.top, this.chart.divHeight - this.chart.padding.bottom])
    // var xScale = d3.scaleLinear()
    //   .domain([d3.min(series, d => d3.min(d, d => d[0])), d3.max(series, d => d3.max(d, d => d[1])) + 20])
    //   .range([this.chart.padding.left, this.chart.divWidth - this.chart.padding.right])
    // var xAxis = d3.axisTop(xScale)
    // var yAxis = d3.axisLeft(yScale)
    // 时间粒度为周的x轴坐标显示还存在一定的问题

    // mainChart.append('g')
    //   .attr('class', 'axisx')
    //   .attr('transform', 'translate(' + 0 + ',' + this.chart.padding.top + ')')
    //   .call(xAxis)
    // 添加每一个刻度的竖线
    mainChart.append('g')
      .attr('class', 'g_line')
      .selectAll('line')
      .data(datadate)
      .join('line')
      .style('opacity', 0.5)
      .attr('stroke', 'black')
      .attr('stroke-width', 0.3)
      .attr('y1', (d) => {
        ticks.push(yScale(d) + yScale.bandwidth() * 0.5)
        return yScale(d) + yScale.bandwidth() * 0.5
      })
      .attr('y2', (d) => {
        return yScale(d) + yScale.bandwidth() * 0.5
      })
      .attr('x1', this.chart.padding.left)
      .attr('x2', this.chart.divWidth - this.chart.padding.right)
    // this.drawriver(mainChart, mainpollution, pollutioncolor, ccolor, series, series1, xScale, ticks)
    // this.changedraw(cityvalue, citymain, change, series, yScale, ticks)
    // 时间刷
    // var brushx = d3.scaleLinear()
    //   .domain([d3.min(series, d => d3.min(d, d => d[0])), d3.max(series, d => d3.max(d, d => d[1])) + 20])
    //   .range([0, 30])
    // var brushy = d3.scaleBand()
    //   .domain(datadate)
    //   .range([this.chart.padding2.top, this.chart.divHeight - this.chart.padding2.bottom])
    // var brushAxis = d3.axisTop(brushx)
    // var brushyAxis = d3.axisLeft(brushy)
    // miniChart.append('g')
    //   .attr('class', 'axisy')
    //   .call(brushyAxis)
    // miniChart.append('g')
    //   .attr('class', 'axisx')
    //   .attr('transform', 'translate(' + 0 + ',' + this.chart.padding2.top + ')')
    //   .call(brushAxis)
    // this.drawriver(miniChart, mainpollution, pollutioncolor, ccolor, series, series1, brushx, ticks)
    var tt = this
    var brush = d3.brushY()
      .extent([
        [0, ticks[0]],
        [30, ticks[series[0].length - 1]]
      ])
      .on('end', brushed)
    miniChart.append('g')
      .attr('class', 'brush')
      .call(brush)
      .call(brush.move, [ticks[0], ticks[series[0].length - 1]])

    function brushed(event) {
      // if (event.sourceEvent && event.sourceEvent.type === 'zoom') {
      //   return
      // }
      mainChart.selectAll('.area')
        .remove()
      mainChart.selectAll('.axisx')
        .remove()
      mainChart.selectAll('.axisy')
        .remove()
      mainChart.selectAll('.g_line')
        .remove()
      // console.log(d3.brushSelection(this))
      var y0 = (d3.brushSelection(this)[0] - ticks[0]) / (ticks[1] - ticks[0])
      var y1 = (d3.brushSelection(this)[1] - ticks[0]) / (ticks[1] - ticks[0])
      var y0int = parseInt(y0)
      var y1int = parseInt(y1)
      var y0float = y0 - y0int
      var y1float = y1 - y1int
      if (y0float >= 0.5) {
        y0int = y0int + 1
      }
      if (y1float >= 0.5) {
        y1int = y1int + 1
      }
      var valuelist = []
      var mainlist = []
      for (var j = y0int; j <= y1int; j++) {
        valuelist.push(cityvalue[j])
        mainlist.push(citymain[j])
      }
      var datee = []
      for (var k = 0; k < valuelist.length; k++) {
        datee.push(valuelist[k].date)
      }
      let dateRange = [datee[0], datee[datee.length - 1]]
      tt.vue.updateTransfer(dateRange)
      // console.log(datee)
      // mainChart.selectAll('.area')
      //   .remove()
      var series = d3.stack()
        .keys(citygroup)
        .offset(d3.stackOffsetWiggle)
        .order(d3.stackOrderInsideOut)(valuelist)

      var changetick = []
      var yScale = d3.scaleBand()
        .domain(datee)
        .range([tt.chart.padding.top, tt.chart.divHeight - tt.chart.padding.bottom])
      var xScale = d3.scaleLinear()
        .domain([d3.min(series, d => d3.min(d, d => d[0])), d3.max(series, d => d3.max(d, d => d[1])) + 20])
        .range([tt.chart.padding.left, tt.chart.divWidth - tt.chart.padding.right])
      // var xAxis = d3.axisTop(xScale)
      var yAxis = d3.axisLeft(yScale)
      // 时间粒度为周的x轴坐标显示还存在一定的问题
      var xmonth = []
      var xyear = []
      var count
      mainChart.append('g')
        .attr('class', 'axisy')
        .attr('transform', 'translate(' + tt.chart.padding.left + ',' + 0 + ')')
        .call(yAxis.tickSizeOuter(0).tickFormat((d, i) => {
          // console.log(d, i)
          var list1 = d.split('-')
          xyear.push(list1[0])
          xmonth.push(list1[1])
          if (list1.length === 2) {
            if (parseInt(list1[1]) === 1) {
              return d
            } else {
              return list1[1]
            }
          } else {
            if (i === 0) {
              count = 1
              return list1[0]
            } else {
              if (d === '2013-01-01' || d === '2014-01-07' || d === '2015-01-06' || d === '2016-01-05' || d === '2017-01-03' || d === '2018-01-02') {
                count = 1
                return list1[0]
              } else {
                count = count + 1
                if (parseInt(count % 6) === 0) {
                  return list1[1] + '-' + list1[2]
                }
              }
            }
          }
        }))

      // mainChart.append('g')
      //   .attr('class', 'axisx')
      //   .attr('transform', 'translate(' + 0 + ',' + tt.chart.padding.top + ')')
      //   .call(xAxis)
      // 添加每一个刻度的竖线
      mainChart.append('g')
        .attr('class', 'g_line')
        .selectAll('line')
        .data(datee)
        .join('line')
        .style('opacity', 0.5)
        .attr('stroke', 'black')
        .attr('stroke-width', 0.3)
        .attr('y1', (d) => {
          changetick.push(yScale(d) + yScale.bandwidth() * 0.5)
          return yScale(d) + yScale.bandwidth() * 0.5
        })
        .attr('y2', (d) => {
          return yScale(d) + yScale.bandwidth() * 0.5
        })
        .attr('x1', tt.chart.padding.left)
        .attr('x2', tt.chart.divWidth - tt.chart.padding.right)
      var mainpollution = ['PM2.5', 'PM10', 'SO2', 'NO2', 'CO', 'O3']
      var pollutioncolor = ['#deb89e', '#997c61', '#7b6b57', '#654047', '#3e3123', '#c1888c']
      // pollutioncolor = ['#84c45e', '#f9d92a', '#fda300', '#ff3406', '#cf0032', '#49224f']
      var series1 = d3.stack()
        .keys(citygroup)
        .offset(d3.stackOffsetWiggle)
        .order(d3.stackOrderInsideOut)(mainlist)
      var ccolor = []
      for (var m = 0; m < series.length; m++) {
        var citycolor = []
        var cityc = series[m].key
        for (var n = 0; n < series[m].length; n++) {
          var citypo = series1[m][n]['data'][cityc]
          for (var t = 0; t < mainpollution.length; t++) {
            if (citypo === mainpollution[t]) {
              break
            }
          }
          citycolor.push(pollutioncolor[t])
        }
        ccolor.push(citycolor)
      }
      // console.log(listt)
      tt.drawriver(mainChart, mainpollution, pollutioncolor, ccolor, series, series1, xScale, changetick, datee)
    }
  }
  drawriver(svg, mainpollution, pollutioncolor, ccolor, series, series1, xScale, ticks, datee) {
    console.log(series)
    var len = (ticks[1] - ticks[0]) / 4
    // 图例
    // for (var c = 0; c < pollutioncolor.length; c++) {
    //   this.chart.svg.append('rect')
    //     .attr('x', width - this.chart.padding.right + 5)
    //     .attr('y', height / 3 + c * 30)
    //     .attr('width', 20)
    //     .attr('height', 20)
    //     .attr('fill', pollutioncolor[c])
    //   this.chart.svg.append('text')
    //     .attr('x', width - this.chart.padding.right + 25)
    //     .attr('y', height / 3 + c * 30 + 15)
    //     .attr('font-size', '8px')
    //     .attr('font-family', 'sans-serif')
    //     .text(mainpollution[c])
    // }
    // 绘制河流
    var alllen = 0
    var ydata = []
    for (var u = 0; u < series.length; u++) {
      for (var v = 0; v < series[u].length; v++) {
        ydata.push(series[u][v][0])
      }
    }
    for (var i = 0; i < series.length; i++) {
      var city = series[i].key
      var gpath = svg.append('g')
        .attr('class', 'area')
      for (var j = 0; j < series[i].length; j++) {
        var citypollution = series1[i][j]['data'][city]
        // console.log(citypollution)
        for (var k = 0; k < mainpollution.length; k++) {
          if (citypollution === mainpollution[k]) {
            // console.log(k);
            break
          }
        }
        // 绘制每个刻度上的方块
        var citypath = 'M ' + parseFloat(xScale(series[i][j][1])) + ' ' + parseFloat(ticks[j] - len) + ' L ' +
          parseFloat(xScale(series[i][j][1])) + ' ' + parseFloat(ticks[j] + len) + ' L ' + parseFloat(xScale(series[i][j][0])) +
          ' ' + parseFloat(ticks[j] + len) + ' L ' + parseFloat(xScale(series[i][j][0])) + ' ' +
          parseFloat(ticks[j] - len) + 'Z'
        gpath.append('path')
          .datum(series[i])
          .attr('d', citypath)
          .attr('fill', pollutioncolor[k])
          .on('click', (d, i) => {
            var xpath = parseInt((d.y - 20) / (ticks[1] - ticks[0]))
            this.vue.selectDate = datee[xpath]
            this.vue.dateChange()
          })
        // 绘制方块之间的path，添加渐变
        if (j < series[i].length - 1) {
          var pathd = 'M ' + parseFloat(xScale(series[i][j][1])) + ' ' + parseFloat(ticks[j] + len) + ' L ' +
            parseFloat(xScale(series[i][j + 1][1])) + ' ' + parseFloat(ticks[j + 1] - len) + ' L ' + parseFloat(xScale(series[i][j + 1][0])) +
            ' ' + parseFloat(ticks[j + 1] - len) + ' L ' + parseFloat(xScale(series[i][j][0])) + ' ' + parseFloat(ticks[j] + len) +
            ' L ' + parseFloat(xScale(series[i][j][1])) + ' ' + parseFloat(ticks[j] + len) + ' Z'
          // console.log(path_d);
          var gradient = gpath.append('defs')
            .append('linearGradient')
            .attr('id', 'linearGradient' + alllen)
            .attr('x1', '0%')
            .attr('y1', '0%')
            .attr('x2', '0%')
            .attr('y2', '100%')
          gradient.append('stop')
            .attr('offset', '0%')
            .attr('stop-color', ccolor[i][j])
          gradient.append('stop')
            .attr('offset', '100%')
            .attr('stop-color', ccolor[i][j + 1])
          gpath.append('path')
            .attr('d', pathd)
            .attr('fill', 'url(#linearGradient' + alllen + ')')

          gpath.append('line')
            .attr('stroke', 'black')
            .attr('stroke-width', 0.4)
            .attr('y1', ticks[j] - len)
            .attr('y2', ticks[j] + len)
            .attr('x1', xScale(series[i][j][0]))
            .attr('x2', xScale(series[i][j][0]))
          gpath.append('line')
            .attr('stroke', 'black')
            .attr('stroke-width', 0.4)
            .attr('y1', ticks[j] + len)
            .attr('y2', ticks[j + 1] - len)
            .attr('x1', xScale(series[i][j][0]))
            .attr('x2', xScale(series[i][j + 1][0]))
        }
        alllen++
        if (i === parseInt(d3.maxIndex(ydata) / series[0].length) && j !== series[i].length - 1) {
          gpath.append('line')
            .attr('stroke', 'black')
            .attr('stroke-width', 0.4)
            .attr('y1', ticks[j] - len)
            .attr('y2', ticks[j] + len)
            .attr('x1', xScale(series[i][j][1]))
            .attr('x2', xScale(series[i][j][1]))
          gpath.append('line')
            .attr('stroke', 'black')
            .attr('stroke-width', 0.4)
            .attr('y1', ticks[j] + len)
            .attr('y2', ticks[j + 1] - len)
            .attr('x1', xScale(series[i][j][1]))
            .attr('x2', xScale(series[i][j + 1][1]))
        }
        if (i !== parseInt(d3.maxIndex(ydata) / series[0].length) && j === series[i].length - 1) {
          gpath.append('line')
            .attr('stroke', 'black')
            .attr('stroke-width', 0.4)
            .attr('y1', ticks[j] - len)
            .attr('y2', ticks[j] + len)
            .attr('x1', xScale(series[i][j][0]))
            .attr('x2', xScale(series[i][j][0]))
        }
        if (i === parseInt(d3.maxIndex(ydata) / series[0].length) && j === series[i].length - 1) {
          gpath.append('line')
            .attr('stroke', 'black')
            .attr('stroke-width', 0.4)
            .attr('y1', ticks[j] - len)
            .attr('y2', ticks[j] + len)
            .attr('x1', xScale(series[i][j][1]))
            .attr('x2', xScale(series[i][j][1]))
        }
      }
      gpath.on('mouseover', function() {
        d3.selectAll('.area')
          .style('opacity', 0.3)
        d3.select(this)
          .style('opacity', 1)
      })
        .on('mouseout', function() {
          d3.selectAll('.area')
            .style('opacity', 1)
        })
        .append('title')
        .text(series[i].key)
    }
  }
  // changedraw(cityvalue, citymain, change, series, yScale, ticks) {
  //   // var citygroup = []
  //   var alldate = []
  //   for (var i = 0; i < cityvalue.length; i++) {
  //     alldate.push(cityvalue[i].date)
  //   }
  //   console.log(alldate)
  //   // console.log(change_data[0]['out_date'])  得到输出日期
  //   for (var j = 0; j < change.length; j++) {
  //     var outdate = change[j]['out_date']
  //     var indate = change[j]['in_date']
  //     var outcity = change[j]['out_city']
  //     var incity = change[j]['in_city']
  //     for (var k = 0; k < alldate.length; k++) {
  //       // 转出时间  x1
  //       if (outdate === alldate[k]) {
  //         var x1 = ticks[k]
  //         // console.log(x1)
  //         var flag1 = k
  //       }
  //       // 转入时间 x2
  //       if (indate === alldate[k]) {
  //         var x2 = ticks[k]
  //         // console.log(x2)
  //         var flag2 = k
  //       }
  //     }
  //     for (var m = 0; m < series.length; m++) {
  //       if (outcity === series[m].key && series[m][flag1]['data']['date'] === outdate) {
  //         var y1 = (series[m][flag1][1] - series[m][flag1][0]) / 2 + series[m][flag1][0]
  //         // console.log(y1)
  //       }
  //       if (incity === series[m].key && series[m][flag2]['data']['date'] === indate) {
  //         var y2 = (series[m][flag2][1] - series[m][flag2][0]) / 2 + series[m][flag2][0]
  //         // console.log(y2)
  //       }
  //     }
  //     this.chart.svg.append('line')
  //       .attr('stroke', 'black')
  //       .attr('stroke-width', 2)
  //       .attr('x1', x1)
  //       .attr('x2', x2)
  //       .attr('y1', yScale(y1))
  //       .attr('y2', yScale(y2))
  //   }
  // }
}
